import ApiFetchers from "@/apis/api_fetchers"
import { createLogger } from "@/utils/logger"
import { useCallback, useState } from "react"
import { useNavigate } from "react-router-dom"
import { toast } from "react-toastify"

const logger = createLogger("useAvatarSubmit")
interface UseAvatarSubmitProps {
    onSuccess?: () => void
    onError?: (error: Error) => void
}

export function useAvatarSubmit({ onSuccess, onError }: UseAvatarSubmitProps = {}) {
    const navigate = useNavigate()
    const [uploading, setUploading] = useState(false)

    const urlToFile = useCallback(async (url: string): Promise<File> => {
        try {
            const response = await fetch(url)
            const blob = await response.blob()
            const fileName = url.split("/").pop() || "avatar.png"
            return new File([blob], fileName, { type: blob.type })
        } catch (error) {
            logger.debug("Convert URL to File failed:", error)
            throw new Error("Failed to convert image URL to file")
        }
    }, [])

    const uploadAvatar = useCallback(
        async (avatarUrl: string) => {
            if (!avatarUrl) return

            setUploading(true)
            try {
                const file = await urlToFile(avatarUrl)

                const result = await ApiFetchers.uploadFile(file)

                if (result) {
                    onSuccess?.()
                    navigate("/s-account")
                    return result
                } else {
                    throw new Error("Upload failed")
                }
            } catch (error) {
                const errorMessage = error instanceof Error ? error.message : "Upload failed"
                toast.error(errorMessage)
                logger.debug("Upload avatar failed:", error)
                onError?.(error instanceof Error ? error : new Error(errorMessage))
            } finally {
                setUploading(false)
            }
        },
        [navigate, urlToFile, onSuccess, onError],
    )
    return {
        uploading,
        uploadAvatar,
    }
}
